<template>
  <div class="mainBox">
    <div class="routerMsg">{{ routerMsg }}</div>
    <div class="container">
      <div class="btnBox" v-permission="'roleManagementAdd'">
        <div class="addBtn">
          <el-button type="success" @click="addRole('')">添加</el-button>
        </div>
      </div>
      <div class="tableBox">
        <el-table
          :data="tableData"
          style="width: 100%; margin-bottom: 20px"
          row-key="id"
        >
          <el-table-column
            align="center"
            :show-overflow-tooltip="true"
            prop="id"
            label="角色编号"
          >
          </el-table-column>
          <el-table-column
            align="center"
            :show-overflow-tooltip="true"
            prop="roleName"
            label="角色名"
          >
          </el-table-column>
          <el-table-column
            align="center"
            :show-overflow-tooltip="true"
            prop="dataScopeName"
            label="数据权限"
          >
          </el-table-column>
          <el-table-column
            align="center"
            :show-overflow-tooltip="true"
            prop="roleSort"
            label="排序值"
          >
          </el-table-column>
          <el-table-column
            width="200"
            align="center"
            prop="address"
            label="操作"
          >
            <template slot-scope="scope">
              <el-button
                style="color: #269e8f"
                type="text"
                @click="addRole(scope.row)"
                v-permission="'roleManagementEdit'"
                >编辑</el-button
              >
              <el-button
                style="color: #269e8f"
                type="text"
                @click="limitAuthority(scope.row)"
                v-permission="'roleManagementAuthority'"
                >权限配置</el-button
              >
              <el-button
                style="color: #f56c6c"
                type="text"
                @click="deleteRole(scope.row)"
                v-permission="'roleManagementDel'"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>

      <el-dialog
        :visible.sync="dialogVisible"
        width="1218px"
        :before-close="handleClose"
        :show-close="false"
        :append-to-body="true"
        custom-class="dialogCompany"
      >
        <div class="dialogTitle" slot="title">{{ dialogTitle }}</div>
        <div class="dialogForm">
          <el-form ref="form" :model="form" label-width="200px" :inline="true">
            <div class="formBox">
              <div class="formItem">
                <div class="left">
                  <el-form-item label="角色名">
                    <el-input
                      :disabled="seeForm"
                      placeholder="请输入"
                      v-model="form.roleName"
                    ></el-input>
                  </el-form-item>
                </div>
                <div class="right">
                  <el-form-item label="排序值">
                    <el-input
                      :disabled="seeForm"
                      placeholder="请输入"
                      type="number"
                      v-model="form.roleSort"
                    ></el-input>
                  </el-form-item>
                </div>
              </div>
              <div class="formItem">
                <div class="left">
                  <el-form-item label="数据权限">
                    <el-select
                      v-model="form.dataScope"
                      placeholder="请选择"
                      :disabled="seeForm"
                    >
                      <el-option
                        v-for="item in dataScopeList"
                        :key="item.id"
                        :label="item.dictName"
                        :value="item.dictCode"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </div>
              </div>
            </div>
          </el-form>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button @click="handleClose">取 消</el-button>
          <el-button
            :disabled="seeForm"
            class="leftCancel"
            type="primary"
            @click="submitForm"
            >确 定</el-button
          >
        </div>
      </el-dialog>
      <el-dialog
        :visible.sync="limitDialog"
        width="848px"
        :before-close="handleClose"
        :show-close="false"
        :append-to-body="true"
        custom-class="dialogCompany"
      >
        <div class="dialogTitle" slot="title">权限配置</div>
        <div class="dialogForm2">
          <div class="roleBox">角色名： {{ roleForm.roleName }}</div>
          <div class="treeBox">
            <div class="treeTitle">权限选择：</div>
            <div class="treeItem">
              <el-tree
                ref="dept"
                :data="treeData"
                show-checkbox
                node-key="id"
                :props="defaultProps"
                @check="chooseTreeData"
              >
              </el-tree>
            </div>
          </div>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button @click="handleCloseRole">取 消</el-button>
          <el-button
            :disabled="seeForm"
            class="leftCancel"
            type="primary"
            @click="submitRole"
            >确 定</el-button
          >
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import {
  roleList,
  dict,
  roleAdd,
  roleUpdate,
  roleDelete,
  roleDetail,
  roleUpdateRoleMenu,
} from '@/api/systemManagement/roleManagement'
export default {
  name: 'menuManagement',
  props: {},
  components: {},
  data() {
    return {
      routerMsg: '',
      searchObj: {
        targetName: '',
        equipName: '',
      },
      tableData: [],
      emergency_scene_codeList: [],
      target_typeList: [],
      form: {
        roleName: '',
        roleSort: '',
        dataScope: '',
      },
      dialogTitle: '添加菜单',
      dialogVisible: false,
      seeForm: false,
      treeData: [],
      defaultProps: {
        children: 'menuList',
        label: 'menuName',
      },
      limitDialog: false,
      dataScopeList: [],
      checkedKeys: [],
      subRoleList: [],
      roleForm: {},
    }
  },
  methods: {
    searchList() {},
    resetSearch() {},
    addRole(msg) {
      if (msg) {
        this.form = msg
        this.dialogTitle = '编辑角色'
      } else {
        this.dialogTitle = '新增角色'
      }
      this.dialogVisible = true
    },
    async deleteRole(row) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          const res = await roleDelete({ id: row.id })
          if (res.data) {
            this.$message({
              type: 'success',
              message: '删除成功!',
            })
            this.getRoleList()
          } else {
            this.$message.error('删除失败')
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          })
        })
    },
    handleClose() {
      this.dialogVisible = false
      this.form = {
        roleName: '',
        roleSort: '',
        dataScope: '',
      }
    },
    async submitForm() {
      if (!this.form.id) {
        const res = await roleAdd(this.form)
        this.formSuccess(res)
      } else {
        const res = await roleUpdate(this.form)
        this.formSuccess(res)
      }
      this.handleClose()
    },
    formSuccess(res) {
      if (res.data) {
        this.$message.success('编辑成功')
        this.getRoleList()
      } else {
        this.$message.error(res.data)
      }
    },
    async limitAuthority(row) {
      this.roleForm = row
      this.limitDialog = true
      const res = await roleDetail({ id: row.id })

      this.$nextTick(() => {
        this.checkedKeys = this.extractIdsByStatus(res.data)

        this.checkedKeys.forEach((v) => {
          this.$nextTick(() => {
            this.$refs.dept.setChecked(v, true, false)
          })
        })
      })
      // console.log(this.checkedKeys)
      this.treeData = res.data
    },
    extractIdsByStatus(tree, result = [], status = '1') {
      tree.forEach((node) => {
        // 检查当前节点的 status 是否为指定的值
        if (node.status === status) {
          // 如果是，则将节点的 id 添加到结果数组中
          result.push(node.id)
        }
        // 如果当前节点有子节点，递归调用函数处理子节点
        if (node.menuList && node.menuList.length) {
          this.extractIdsByStatus(node.menuList, result, status)
        }
      })
      return result
    },
    async submitRole() {
      const obj = {
        id: this.roleForm.id,
        menuList: this.subRoleList,
      }
      const res = await roleUpdateRoleMenu(obj)
      if (res.data) {
        this.$message.success('设置成功')
        this.handleCloseRole()
      } else {
        this.$message.error(res.data)
      }
    },
    chooseTreeData(row, val) {
      // console.log(row, val)
      const array1 = val.checkedNodes.map((item) => {
        return {
          id: item.id,
        }
      })
      const array2 = val.halfCheckedNodes.map((item) => {
        return {
          id: item.id,
        }
      })
      this.subRoleList = [...array1, ...array2]
    },
    handleCloseRole() {
      this.limitDialog = false
      this.roleForm = {}
      this.checkedKeys = []
    },
    async getRoleList() {
      const res = await roleList()
      // console.log(res)
      this.tableData = res.data
    },
    async getDataScopeDict() {
      const res = await dict({ dictType: 'data_scope' })
      // console.log(res)
      this.dataScopeList = res.data
    },
  },
  created() {
    this.routerMsg = this.$route.meta.title
    this.getRoleList()
    this.getDataScopeDict()
  },
  mounted() {},
  watch: {},
  computed: {},
  filters: {},
}
</script>

<style scoped lang="scss">
.routerMsg {
  padding: 20px;
  color: #999999;
  font-size: 14px;
}
.mainBox {
  width: 100%;
}

.container {
  height: 100%;
  background-color: #fff;
  border-radius: 8px;
  width: 100%;
  box-sizing: border-box;
  padding: 20px 25px;
  .searchBox {
    display: flex;
    margin-bottom: 20px;
    .search1 {
      margin-right: 15px;
    }
    .searchBtn {
      .el-button {
        border: 1px solid #269e8f;
        color: #269e8f;
      }
      .reset {
        border: 1px solid #269e8f;
        color: #fff;
        background-color: #269e8f;
        margin-left: 20px;
      }
    }
  }
  .btnBox {
    display: flex;
    margin-bottom: 15px;
    .addBtn {
      margin-right: 20px;
      .el-button {
        background-color: #269e8f;
        border: 1px solid #269e8f;
      }
    }
  }
  .footerPage {
    padding-top: 20px;
    text-align: right;
    padding-right: 30px;
    ::v-deep .el-pagination.is-background .el-pager li:not(.disabled).active {
      background-color: #2aa59e !important; // 进行修改选中项背景和字体
      color: #fff;
    }
    .totalNum {
      font-size: 14px;
      font-weight: normal;
      margin-right: 10px;
    }
  }
}

.dialogTitle {
  text-align: center;
  border-bottom: 1px solid #d8d8d8;
  font-size: 20px;
  font-weight: 500;
  padding: 22px 0 19px 0;
}
::v-deep .el-dialog__header {
  padding: 0 30px;
}
.dialog-footer {
  display: flex;
  justify-content: center;
  .leftCancel {
    margin-left: 77px;
    background-color: #269e8f;
    border: 1px solid #269e8f;
  }
}
.dialogForm {
  .treeBox {
    margin-top: 10px;
    display: flex;
  }
  .formBox {
    .formItem {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;
    }
    .left {
      width: 50%;
      height: 30px;
      line-height: 30px;
    }
    .right {
      width: 50%;
      height: 30px;
      line-height: 30px;
    }
    ::v-deep .el-input {
      height: 30px;
      width: 260px;
    }
    ::v-deep .el-input__inner {
      height: 30px;
    }
    ::v-deep .el-input__suffix {
      height: 40px;
    }
  }
}
.dialogForm2 {
  padding: 10px;
  .treeBox {
    margin-top: 10px;
    display: flex;
    .treeItem {
      width: 80%;
    }
  }
}
::v-deep.dialogCompany {
  border-radius: 20px;
}
</style>
